package cs276.pe1.lucene;

import java.io.IOException;
import java.util.logging.Logger;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

/**
 * IMDBSearcher class
 * @author alecmgo@gmail.com
 *
 */
public class IMDBSearcher {
  private static Logger logger = Logger.getLogger("cs276.pe1.lucene.IMDBSearcher");

  private static int RESULT_SET_SIZE = 20;
  private static String DEFAULT_FIELD = "plots";
  private IndexSearcher indexSearcher;
  private static boolean verbose = true;

  public IMDBSearcher() throws Exception {
    indexSearcher = new IndexSearcher(System.getProperty("user.home") + "/cs276-index");  
  }
  
  protected void finalize() throws Throwable {    
    indexSearcher.close();
  }

  public void search(String query) throws IOException, ParseException {
    search(query, DEFAULT_FIELD);
  }

  public void search(String searchWord, String defaultField) throws IOException, ParseException {
    QueryParser parser = new QueryParser(DEFAULT_FIELD, new StandardAnalyzer());
    Query query = parser.parse(searchWord);

    Hits hits = indexSearcher.search(query);

    System.out.println(hits.length() + " search results for query " + searchWord);
    for(int i = 0; i < Math.min(RESULT_SET_SIZE, hits.length()); i++) {
      if(verbose) {
        System.out.println("\nResult " + (i + 1));
        System.out.println("Title: " + hits.doc(i).getField("title").stringValue());
        System.out.println("Author: " + hits.doc(i).getField("authors").stringValue());
        System.out.println("Plot: " + hits.doc(i).getField("plots").stringValue());
      } else {
        System.out.println((i + 1) + ": " + hits.doc(i).getField("title").stringValue());
      }
    }
  }

  public static boolean isVerbose() {
    return verbose;
  }

  public static void setVerbose(boolean verbose) {
    IMDBSearcher.verbose = verbose;
  }

  public static void main(String[] args) throws Exception{
    IMDBSearcher searcher = new IMDBSearcher();
    searcher.search("authors:Rob");
    searcher.search("plots:(\"eighteen murdered\"~5)");
    searcher.search("title:(10 items or less(2006))");
  }
}
